<template>
    <div class="order-container">
        <div class="page-header">
            <h1 class="page-title">我的订单</h1>
            <p class="page-subtitle">查看和管理您的订单信息</p>
        </div>
        
        <!-- 订单状态筛选 -->
        <div class="order-filters">
            <el-tabs v-model="activeTab" @tab-change="handleTabChange">
                <el-tab-pane label="全部订单" name="all" />
                <el-tab-pane label="待付款" name="pending" />
                <el-tab-pane label="待发货" name="paid" />
                <el-tab-pane label="待收货" name="shipped" />
                <el-tab-pane label="已完成" name="completed" />
                <el-tab-pane label="已取消" name="cancelled" />
            </el-tabs>
        </div>
        
        <!-- 订单列表 -->
        <div class="order-list">
            <div
                v-for="order in orders"
                :key="order.id"
                class="order-card"
            >
                <div class="order-header">
                    <div class="order-info">
                        <span class="order-number">订单号：{{ order.order_number }}</span>
                        <span class="order-time">{{ formatTime(order.created_at) }}</span>
                    </div>
                    <div class="order-status">
                        <el-tag :type="getStatusType(order.status)">
                            {{ getStatusText(order.status) }}
                        </el-tag>
                    </div>
                </div>
                
                <div class="order-items">
                    <div
                        v-for="item in order.items"
                        :key="item.id"
                        class="order-item"
                    >
                        <div class="item-image">
                            <img :src="item.image" :alt="item.name" />
                        </div>
                        <div class="item-info">
                            <h4 class="item-name">{{ item.name }}</h4>
                            <p class="item-specs">{{ item.specifications }}</p>
                            <div class="item-price-qty">
                                <span class="price">¥{{ item.price }}</span>
                                <span class="quantity">x{{ item.quantity }}</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="order-footer">
                    <div class="order-total">
                        <span class="total-text">
                            共{{ order.items.length }}件商品 合计：
                        </span>
                        <span class="total-amount">¥{{ order.total_amount }}</span>
                    </div>
                    
                    <div class="order-actions">
                        <el-button
                            v-if="order.status === 'pending'"
                            type="primary"
                            @click="payOrder(order)"
                        >
                            立即付款
                        </el-button>
                        
                        <el-button
                            v-if="order.status === 'shipped'"
                            type="success"
                            @click="confirmReceive(order)"
                        >
                            确认收货
                        </el-button>
                        
                        <el-button
                            v-if="order.status === 'completed'"
                            @click="reviewOrder(order)"
                        >
                            评价订单
                        </el-button>
                        
                        <el-button
                            v-if="['pending', 'paid'].includes(order.status)"
                            @click="cancelOrder(order)"
                        >
                            取消订单
                        </el-button>
                        
                        <el-button
                            @click="viewOrderDetail(order)"
                            type="text"
                        >
                            查看详情
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 空状态 -->
        <el-empty v-if="orders.length === 0" description="暂无订单">
            <el-button type="primary" @click="goToShopping">
                去购物
            </el-button>
        </el-empty>
        
        <!-- 分页 -->
        <div class="pagination" v-if="total > pageSize">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handlePageChange"
            />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, changeOrder, goPay } from '@/api/shopping'

const router = useRouter()

const orders = ref([])
const loading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取订单列表
const fetchOrders = async () => {
    loading.value = true
    try {
        const data = await getOrder({
            status: activeTab.value === 'all' ? undefined : activeTab.value,
            page: currentPage.value,
            page_size: pageSize.value
        })
        
        // 处理订单数据
        orders.value = (data.results || data || []).map(order => ({
            id: order.id,
            order_number: order.order_number || `ORDER${order.id}`,
            status: order.status || 'pending',
            total_amount: order.total_amount || 0,
            created_at: order.created_at,
            items: order.items || order.commodities || []
        }))
        
        total.value = data.count || orders.value.length
        
    } catch (error) {
        console.error('获取订单失败:', error)
        ElMessage.error('获取订单失败')
    } finally {
        loading.value = false
    }
}

// 处理标签切换
const handleTabChange = (tabName) => {
    activeTab.value = tabName
    currentPage.value = 1
    fetchOrders()
}

// 处理分页变化
const handlePageChange = (page) => {
    currentPage.value = page
    fetchOrders()
}

const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    fetchOrders()
}

// 获取状态类型
const getStatusType = (status) => {
    const statusMap = {
        'pending': 'warning',
        'paid': 'info',
        'shipped': 'primary',
        'completed': 'success',
        'cancelled': 'danger'
    }
    return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        'pending': '待付款',
        'paid': '待发货',
        'shipped': '待收货',
        'completed': '已完成',
        'cancelled': '已取消'
    }
    return statusMap[status] || '未知状态'
}

// 支付订单
const payOrder = async (order) => {
    try {
        const paymentUrl = await goPay(order.id)
        if (paymentUrl) {
            // 跳转到支付页面
            window.open(paymentUrl, '_blank')
        } else {
            ElMessage.success('支付成功')
            fetchOrders()
        }
    } catch (error) {
        console.error('支付失败:', error)
        ElMessage.error('支付失败')
    }
}

// 确认收货
const confirmReceive = async (order) => {
    try {
        await ElMessageBox.confirm('确认已收到商品？', '确认收货', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'info'
        })
        
        await changeOrder(order.id)
        ElMessage.success('确认收货成功')
        fetchOrders()
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('确认收货失败:', error)
            ElMessage.error('确认收货失败')
        }
    }
}

// 取消订单
const cancelOrder = async (order) => {
    try {
        await ElMessageBox.confirm('确定要取消这个订单吗？', '取消订单', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await changeOrder(order.id)
        ElMessage.success('订单已取消')
        fetchOrders()
        
    } catch (error) {
        if (error !== 'cancel') {
            console.error('取消订单失败:', error)
            ElMessage.error('取消订单失败')
        }
    }
}

// 评价订单
const reviewOrder = (order) => {
    ElMessage.info('评价功能开发中...')
}

// 查看订单详情
const viewOrderDetail = (order) => {
    router.push({
        name: 'OrderDetail',
        params: { id: order.id }
    })
}

// 跳转到购物页面
const goToShopping = () => {
    router.push({ name: 'Shopping' })
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return '未知时间'
    return new Date(timeString).toLocaleString('zh-CN')
}

onMounted(() => {
    fetchOrders()
})
</script>

<style lang="less" scoped>
.order-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 30px;
    text-align: center;
    
    .page-title {
        font-size: 32px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
    }
    
    .page-subtitle {
        color: #7f8c8d;
        font-size: 16px;
        margin: 0;
    }
}

.order-filters {
    margin-bottom: 30px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    
    :deep(.el-tabs__header) {
        margin: 0;
        padding: 0 20px;
    }
    
    :deep(.el-tabs__nav-wrap) {
        padding: 0;
    }
}

.order-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .order-card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        overflow: hidden;
        transition: all 0.3s ease;
        
        &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 25px rgba(0, 0, 0, 0.15);
        }
        
        .order-header {
            padding: 20px 24px;
            background: #f8f9fa;
            border-bottom: 1px solid #ecf0f1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            
            .order-info {
                display: flex;
                flex-direction: column;
                gap: 4px;
                
                .order-number {
                    font-weight: 600;
                    color: #2c3e50;
                    font-size: 16px;
                }
                
                .order-time {
                    color: #7f8c8d;
                    font-size: 14px;
                }
            }
        }
        
        .order-items {
            padding: 20px 24px;
            
            .order-item {
                display: flex;
                gap: 16px;
                margin-bottom: 16px;
                
                &:last-child {
                    margin-bottom: 0;
                }
                
                .item-image {
                    width: 80px;
                    height: 80px;
                    border-radius: 8px;
                    overflow: hidden;
                    flex-shrink: 0;
                    
                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }
                }
                
                .item-info {
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    
                    .item-name {
                        font-size: 16px;
                        font-weight: 600;
                        color: #2c3e50;
                        margin-bottom: 4px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                    }
                    
                    .item-specs {
                        color: #7f8c8d;
                        font-size: 14px;
                        margin-bottom: 8px;
                    }
                    
                    .item-price-qty {
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        
                        .price {
                            font-size: 16px;
                            font-weight: 600;
                            color: #e74c3c;
                        }
                        
                        .quantity {
                            color: #7f8c8d;
                            font-size: 14px;
                        }
                    }
                }
            }
        }
        
        .order-footer {
            padding: 20px 24px;
            background: #f8f9fa;
            border-top: 1px solid #ecf0f1;
            display: flex;
            align-items: center;
            justify-content: space-between;
            
            .order-total {
                .total-text {
                    color: #7f8c8d;
                    font-size: 14px;
                }
                
                .total-amount {
                    font-size: 18px;
                    font-weight: 600;
                    color: #e74c3c;
                    margin-left: 8px;
                }
            }
            
            .order-actions {
                display: flex;
                gap: 12px;
                
                .el-button {
                    border-radius: 6px;
                }
            }
        }
    }
}

.pagination {
    margin-top: 40px;
    display: flex;
    justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .order-container {
        padding: 15px;
    }
    
    .order-card {
        .order-header {
            padding: 16px 20px;
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;
        }
        
        .order-items {
            padding: 16px 20px;
            
            .order-item {
                .item-image {
                    width: 60px;
                    height: 60px;
                }
            }
        }
        
        .order-footer {
            padding: 16px 20px;
            flex-direction: column;
            align-items: flex-start;
            gap: 16px;
            
            .order-actions {
                width: 100%;
                justify-content: flex-end;
                flex-wrap: wrap;
            }
        }
    }
}
</style> 